<?php

namespace App\Facades;

use AlibabaCloud\Alidns\Alidns;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Enums\DnsLine;
use App\Enums\DnsType;

class AliyunDns extends AliyunFacade
{
    /**
     * @throws ServerException
     * @throws ClientException
     */
    public function store(string $root, string $rr, string $value, DnsType $type = DnsType::A): void
    {
        $res = Alidns::v20150109()
            ->describeDomainRecords()
            ->withPageNumber(1)
            ->withPageSize(100)
            ->withDomainName($root)
            ->request();
        $records = $res->get('DomainRecords.Record');
        $dns = collect($records)->where('Type', $type->value)->where('RR', $rr)->first();

        if ($dns && $dns['Value'] != $value) {
            Alidns::v20150109()
                ->updateDomainRecord()
                ->withRecordId($dns['RecordId'])
                ->withRR($rr)
                ->withType($type->value)
                ->withValue($value)
                ->withTTL(600)
                ->withLine(DnsLine::DEFAULT->value)
                ->request();
        } else {
            Alidns::v20150109()
                ->addDomainRecord()
                ->withDomainName($root)
                ->withRR($rr)
                ->withType($type->value)
                ->withValue($value)
                ->withTTL(600)
                ->withLine(DnsLine::DEFAULT->value)
                ->request();
        }
    }

    /**
     * 移除域名的解析记录
     *
     * @param  string  $recordId
     * @return void
     * @throws ClientException
     * @throws ServerException
     */
    public function remove(string $recordId): void
    {
        Alidns::v20150109()
            ->deleteDomainRecord()
            ->withRecordId($recordId)
            ->request();
    }
}
